/**
 * 设置信息表单页面
 * wangmei
 */
import React, { Component } from 'react';
import { Modal, Button, Form, Input, message, Select, AutoComplete, Row, Col } from 'antd';
import * as Request from '../../../Server/Upgrade';
import * as Const from '../../../common/const';
import * as Utils from '../../../common/utils';
import qs from 'qs';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

class PopupFrom extends Component{
    constructor(props) {
        super(props);
        this.state = {
            langData: []
        }
    }

    componentWillMount(){
        this.getLangData();
    }

    //保存方法
    handleSubmit = (e) => {
        e.preventDefault();
        const { form, row, id, current, size } = this.props
        form.validateFieldsAndScroll((err, values) => {
            if(!err){
                values.versionId = id;
                values.type = values.type.replace(/\s*/g,"");
                if(row.id==undefined){ //新增
                    values.link = values.link=='http://'?"":values.link
                    const _param = qs.stringify(values);
                    Request.popupInfoSave(_param).then(res => {
                        if(res && res.code == Const.REQUEST_SUCCESS){
                            this.props.showModelFunc({} , false);
                            this.props.getTableData({page: current?current-1:0, size: size(), vId: id});
                            message.success('新增成功！', 1);
                        }else{
                            res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, 2);
                        }
                    });
                }else {
                    values.id = row.id;
                    const _param = qs.stringify(values);
                    Request.popupInfoUpdate(_param).then(res => {
                        if(res && res.code == Const.REQUEST_SUCCESS){
                            this.props.showModelFunc({} , false);
                            this.props.getTableData({page: current?current-1:0, size: size(), vId: id});
                            message.success('修改成功！', 1);
                        }else{
                            res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, 2);
                        }
                    });
                }
            }
        });
    }

    //校验idMain方法
    validateIdMain = (rule, value, callback) =>{
        const { row } = this.props;
        if(value==''||value==undefined){
            callback('请选择泡泡类别！');
            return ;
        }
        if(value.length>250){
            callback('泡泡类别长度不能超过250个字符');
            return ;
        }
        if(value && value.length){
            const params = {type:value, vId: this.props.id, id: row.id?row.id:null};
            Request.popupInfoValidator(qs.stringify(params)).then(res => {
                if(res && Const.REQUEST_SUCCESS == res.code && !res.data){
                    callback('泡泡类别已存在,请重新输入!');
                    return ;
                }else{
                    callback();//注意:回调函数必须调用
                    return ;
                }
            });
        }else{
            callback();
        }
    }

    //语言ID
    getLangData = (name) =>{
        const param = {
            page: 0, 
            size: 50 
        }
        const _param = qs.stringify(param);
        Request.languagesPage(_param).then(res => {
            if(res && res.code == Const.REQUEST_SUCCESS){
                const data = res.data
                this.setState({
                    langData: data.content,
                });
            }else{
                res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    render(){
        const { showModelFunc, row } = this.props;
        const { getFieldDecorator } = this.props.form;
        const { langData } = this.state;
        const langOptions = langData.map(d => <Option value={d.id}>{d.languageNo}</Option>);
        const formItemLayout = {
            labelCol: {
              xs: { span: 24 },
              sm: { span: 6 },
            },
            wrapperCol: {
              xs: { span: 24 },
              sm: { span: 14 },
            },
        };

        //泡泡类别:
        const popupType = ['noupdate', 'unauthorized', 'closeupdatetip', 'busy', 'tonewerversion', 
            'willvalidate', 'enterprise_customize'
        ];

        //类型数据
        const typeData = [
            {
                title: 'text',
                value: 'text',
            }, {
                title: 'embedie',
                value: 'embedie',
            }
        ];
        let linkValue = 'http://';
        if(row.id){
            linkValue = row.link;
            linkValue = linkValue=='http://'?"":linkValue
        }

        return(
            <Modal 
                visible={true}
                width="50%"
                title={row.id?"修改泡泡信息":"新增泡泡信息"}
                footer={null}
                maskClosable={false}
                onCancel={()=>showModelFunc({} , false)}
            >
                <Form onSubmit={this.handleSubmit} >
                    <FormItem
                        {...formItemLayout}
                        label="泡泡类别"
                        >
                        {getFieldDecorator('type',{
                            rules: [{
                                required: true, 
                                validator: this.validateIdMain,
                            }],
                            initialValue: row.type || '',
                        })(
                            <AutoComplete
                                dataSource={popupType}
                                style={{ width: '100%' }}
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="泡泡链接"
                        >
                        {getFieldDecorator('link', {
                            initialValue: linkValue,
                        })(
                            <Input maxLength={250}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="泡泡文字"
                        >
                        {getFieldDecorator('text', {
                            initialValue: Utils.HTMLDecode(row.text) || '',
                        })(
                            <TextArea rows={4} maxLength={4000}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="参数"
                        >
                        {getFieldDecorator('param', {
                            initialValue: row.param || '',
                        })(
                            <Input maxLength={1000}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="类型"
                        >
                        {getFieldDecorator('UIMode', {
                            initialValue: row.uimode || 'text',
                        })(
                            <Select style={{ width: '100%'}} >
                                {
                                    typeData.map((item, index)=>{
                                        return <Option value={item.value} >
                                                {item.title}
                                            </Option>
                                    })
                                }
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="自动关闭时间"
                        >
                        {getFieldDecorator('delay', {
                            initialValue: row.delay || '',
                        })(
                            <Input maxLength={250}/>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="是否等待"
                        >
                        {getFieldDecorator('wait', {
                            initialValue: row.wait || '',
                        })(
                            <Select style={{ width: '100%'}} >
                                <Option value='' >请选择</Option>
                                <Option value='true' >是</Option>
                                <Option value='false' >否</Option>
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="语言编号"
                        >
                        {getFieldDecorator('langId', {
                            rules: [{
                                required: true, 
                                message: '请选择语言编号！'
                            }],
                            initialValue: row.langId?parseInt(row.langId):16
                        })(
                            <Select
                                showSearch
                                style={{ width: '100%' }}
                                optionFilterProp="children"
                                onSelect={this.getLangData}
                                filterOption={true}
                            >
                                {langOptions}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="备注"
                        >
                        {getFieldDecorator('remark', {
                            initialValue: row.remark || '',
                        })(
                            <Input maxLength={250} type="" placeholder="备注，250个字符以内"/>
                        )}
                    </FormItem>
                    <Row type="flex" style={{ textAlign: 'center'}}>
                        <Col span={24}>
                            <FormItem>
                                <Button type="primary" htmlType="submit"  className="conform-button">保存</Button>
                                <Button type="primary" onClick={()=>showModelFunc({} , false)}>返回</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>

            </Modal>
        )
    }
}

export default Form.create()(PopupFrom)